//
//  UISearchBar+common.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/10.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "UISearchBar+common.h"

@implementation UISearchBar (common)

- (void)changeTextFile:(CGFloat)cornerRadius BackgoundColor:(UIColor *)color{
    [self removeBackgroundColor];
    
    UITextField *searchField = [self valueForKey:@"searchField"];
    
    searchField.height = 30;
    searchField.y = 7;
    searchField.backgroundColor = color;
    if (cornerRadius > 0) {
        searchField.layer.cornerRadius = cornerRadius;
        searchField.layer.masksToBounds = YES;
    }
}

- (void)BeautifulSearchBox:(CGFloat)font{
    
    [self removeBackgroundColor];
    
    UITextField *searchField = [self valueForKey:@"searchField"];
    
    searchField.font = [UIFont systemFontOfSize:font];
    searchField.height = 30;
    searchField.y = 7;
    searchField.backgroundColor = [UIColor whiteColor];
    searchField.layer.cornerRadius = 15;
    searchField.layer.masksToBounds = YES;
    searchField.layer.borderWidth = .6;
    searchField.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    
    UIImageView *glassIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"glass"]];
    glassIcon.frame = CGRectMake(0, 0, 15, 15);
    glassIcon.contentMode = UIViewContentModeScaleAspectFit;
    
    searchField.leftViewMode = UITextFieldViewModeAlways;
    searchField.leftView = glassIcon;
}

- (void)HomeSearchBar {
    [self removeBackgroundColor];
    
    [self setLeftPlaceholder:@"搜索"];

    self.backgroundColor     = [UIColor whiteColor];
    self.layer.cornerRadius  = 5;
    self.layer.masksToBounds = YES;
    UITextField *searchField = [self valueForKey:@"searchField"];
    searchField.font = [UIFont systemFontOfSize:14];
}


-(void)setLeftPlaceholder:(NSString *)placeholder {
    self.placeholder = placeholder;
    
    SEL centerSelector = NSSelectorFromString([NSString stringWithFormat:@"%@%@", @"setCenter", @"Placeholder:"]);
    if ([self respondsToSelector:centerSelector]) {
        BOOL centeredPlaceholder = NO;
        NSMethodSignature *signature = [[UISearchBar class] instanceMethodSignatureForSelector:centerSelector];
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        [invocation setTarget:self];
        [invocation setSelector:centerSelector];
        [invocation setArgument:&centeredPlaceholder atIndex:2];
        [invocation invoke];
    }
}

- (void)removeBackgroundColor {
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            for (UIView *subview in view.subviews) {
                if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
                    [subview removeFromSuperview];
                }
            }
        }
    }
}

@end
